<template>
	<view class="add page bgf7 p12">
		<view class="bgff p12">
			<!-- 套餐项列表 -->
			<view v-for="(item, index) in list" :key="item._uid" class="mb16 borb p10">
				<!-- 星期选择 -->
				<view class="flex flexS mb10">
					<text class="mr14 pt3">适用星期</text>
					<view class="days-container">
						<button
							v-for="(day, dayIndex) in days"
							:key="dayIndex"
							@click="toggleDay(index, day)"
							:class="{ 'selected': item.week.includes(day) }"
							class="day-btn"
						>
							{{ day | formatDay }}
						</button>
					</view>
				</view>
				
				<!-- 时间和价格输入 -->
				<view class="flex py6 items-center">
					<input 
						v-model="item.hour" 
						type="digit" 
						class="flex1 bor r10" 
						style="text-align: center;" 
						placeholder="请输入小时数" 
						@input="handleHourInput(item)"
					/>
					<text class="ml8">小时</text>
					<input 
						type="digit" 
						v-model="item.amount" 
						class="flex1 bor r10 px4 ml8" 
						placeholder="请输入套餐价格" 
					/>
					<text class="ml8">元</text>
					<text class="ml8">原价</text>
					<input 
						type="digit" 
						v-model="item.original_amount" 
						class="flex1 bor r10 px4 ml8" 
						placeholder="请输入原价" 
					/>
					<text class="ml8">元</text>
				</view>
				
				<!-- 操作按钮 -->
				<view class="flex btnGroup fs10">
					<button size="mini" type="warn" @click="delItem(item, index)" class="mr8">删除</button>
					<button size="mini" type="primary" @click="copySet(item, index)">复制</button>
				</view>
			</view>
			
			<!-- 底部操作按钮 -->
			<view class="flex flexC aliC mt36">
				<view class="mr30 flex1 c00 bgf6 r40 py12 text-center" @click="addItem">添加套餐项</view>
				<view class="flex1 bg41 r40 py12 text-center text-white" @click="save">保存套餐数据</view>
			</view>
		</view>
		
		<!-- 复制弹窗 -->
		<view class="modal-mask" v-if="showCopyModal" @click="closeModal"></view>
		<view class="modal-container" v-if="showCopyModal">
			<view class="modal-header">
				<text class="modal-title">选择要复制的包厢</text>
				<text class="modal-close" @click="closeModal">×</text>
			</view>
			
			<view class="modal-content" :style="{ maxHeight: modalMaxHeight }">
				<view v-if="loadingRooms" class="loading">加载中...</view>
				
				<view v-if="errorLoadingRooms" class="error">
					加载包厢失败，请重试
					<button @click="fetchRooms" class="retry-btn">重试</button>
				</view>
				
				<view v-if="rooms.length > 0 && !loadingRooms && !errorLoadingRooms" class="room-list">
					<checkbox-group @change="handleRoomSelect">
						<view class="room-item" v-for="room in rooms" :key="room.id">
							<checkbox 
								:checked="selectedRoomIds.includes(room.id.toString())" 
								:value="room.id.toString()"
							>
							<text class="room-name">{{ room.name }}</text>
							</checkbox>
							
						</view>
					</checkbox-group>
				</view>
				
				<view v-if="rooms.length === 0 && !loadingRooms && !errorLoadingRooms" class="no-data">
					暂无包厢数据
				</view>
			</view>
			
			<view class="modal-footer">
				<button size="mini" type="default" @click="closeModal">取消</button>
				<button 
					type="primary" 
					size="mini"
					@click="confirmCopy" 
					:disabled="selectedRoomIds.length === 0"
					:class="{ 'disabled': selectedRoomIds.length === 0 }"
				>
					确定复制
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				room_id: '',
				list: [],
				days: [1, 2, 3, 4, 5, 6, 7], // 1-7对应周一到周日
				
				// 复制弹窗相关数据
				showCopyModal: false,
				rooms: [],
				selectedRoomIds: [],
				loadingRooms: false,
				errorLoadingRooms: false,
				currentItem: null,
				currentIndex: -1,
				modalMaxHeight: '50vh',
				uidCounter: 1 // 用于生成唯一标识
			};
		},
		
		filters: {
			// 格式化星期显示（1→周一，2→周二...）
			formatDay(day) {
				const dayMap = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '日'};
				return dayMap[day] || day;
			}
		},
		
		onLoad(option) {
			this.room_id = option.id || '';
			this.getRoomSetList();
			uni.onWindowResize(this.calculateModalHeight);
		},
		
		onUnload() {
			uni.offWindowResize(this.calculateModalHeight);
		},
		
		methods: {
			// 计算弹窗最大高度
			calculateModalHeight() {
				uni.getSystemInfo({
					success: (res) => {
						this.modalMaxHeight = `${res.windowHeight * 0.7}px`;
					}
				});
			},
			
			// 切换星期选择
			toggleDay(cardIndex, day) {
				const card = this.list[cardIndex];
				if (!card.week) card.week = []; // 确保数组存在
				
				const index = card.week.indexOf(day);
				if (index === -1) {
					card.week.push(day);
				} else {
					card.week.splice(index, 1);
				}
			},
			
			// 限制小时为整数
			handleHourInput(item) {
				item.hour = item.hour.replace(/[^\d]/g, ''); // 只保留数字
			},
			
			//获取复制包厢的列表
			getCopyRoom(){
				
				let param = { room_id: this.room_id };
				this.$api.getCopyRoom(param).then(res => {
					if (res.code === 1) {
						this.loadingRooms = false;
						this.rooms = res.data;
					}
				}).catch(err => {
					console.error('获取套餐列表失败:', err);
					uni.showToast({ title: '数据加载失败', icon: 'none' });
				});
					
			},
			
			// 获取套餐列表
			getRoomSetList() {
				if (!this.room_id) return;
				
				let param = { room_id: this.room_id };
				this.$api.getRoomSet(param).then(res => {
					if (res.code === 1) {
						// 初始化week数组和唯一标识
						this.list = res.data.map(item => ({
							...item,
							week: item.week || [],
							_uid: this.uidCounter++ // 为每个项目添加唯一标识
						}));
					}
				}).catch(err => {
					console.error('获取套餐列表失败:', err);
					uni.showToast({ title: '数据加载失败', icon: 'none' });
				});
			},

			// 删除套餐项
			delItem(item, index) {
				uni.showModal({
					title: '确认删除',
					content: '是否删除当前套餐项？',
					success: (res) => {
						if (res.confirm) {
							if (item.id !== -1) {
								// 已保存的项，调用接口删除
								let param = { id: item.id };
								this.$api.removeRoomSetItem(param).then(res => {
									if (res.code === 1) {
										this.getRoomSetList(); // 重新获取列表
									} else {
										uni.showToast({ title: res.msg, icon: 'none' });
									}
								});
							} else {
								// 未保存的临时项，直接删除
								this.list.splice(index, 1);
							}
						}
					}
				});
			},

			// 添加套餐项
			addItem() {
				// 创建全新的对象，确保没有引用关系
				const newItem = {
					_uid: this.uidCounter++, // 增加唯一标识
					id: -1, // 临时ID标识未保存
					hour: '', // 初始为空，避免默认0导致验证不通过
					amount: '',
					name:'',
					original_amount: '',
					shop_id: '',
					room_id: this.room_id,
					week: [1, 2, 3, 4, 5, 6, 7] // 默认全选
				};
				this.list.push(newItem);
			},
			
			// 保存套餐数据
			save() {
				// 验证数据
				const isValid = this.list.every(item => {
					// 小时和价格必须为大于0的数字
					const hourValid = item.hour && Number(item.hour) > 0;
					const amountValid = item.amount && Number(item.amount) > 0;
					// 星期至少选择一个
					const weekValid = item.week && item.week.length > 0;
					
					return hourValid && amountValid && weekValid;
				});
				
				if (!isValid) {
					uni.showToast({
						title: '请完善套餐信息（时间/价格需大于0，至少选择一个星期）',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 处理提交数据
				const submitList = this.list.map(item => {
					// 提交时剔除临时的_uid属性
					const { _uid, ...submitData } = item;
					return {
						...submitData,
						hour: Number(submitData.hour),
						amount: Number(submitData.amount),
						original_amount: submitData.original_amount ? Number(submitData.original_amount) : 0
					};
				});
				
				let param = {
					id: this.room_id,
					set: JSON.stringify(submitList)
				};
				
				this.$api.addRoomSetItem(param).then(res => {
					if (res.code === 1) {
						uni.showModal({
							title: "成功",
							content: "套餐保存成功",
							showCancel: false,
							complete() {
								uni.navigateBack({ delta: 1 });
							}
						});
					} else {
						uni.showToast({ title: res.msg, icon: 'none' });
					}
				}).catch(err => {
					console.error('保存失败:', err);
					uni.showToast({ title: '保存失败，请重试', icon: 'none' });
				});
			},
			
			// 打开复制弹窗
			copySet(item, index) {
				this.currentItem = { ...item }; // 深拷贝避免引用修改
				this.currentIndex = index;
				this.selectedRoomIds = [];
				this.showCopyModal = true;
				this.errorLoadingRooms = false;
				this.calculateModalHeight();
				this.fetchRooms();
			},
			
			// 获取包厢列表
			fetchRooms() {
				this.loadingRooms = true;
				this.errorLoadingRooms = false;
				this.getCopyRoom();
			},
			
			// 处理包厢选择
			handleRoomSelect(e) {
				this.selectedRoomIds = e.detail.value || [];
			},
			
			// 确认复制
			confirmCopy() {
				if (this.selectedRoomIds.length === 0) return;
				
				uni.showLoading({ title: '复制中...' });
				// 准备复制数据（排除原ID和临时标识）
				const { id, _uid, ...copyData } = this.currentItem;
				
				this.$api.copyRoomSet({
					targetRoomIds: JSON.stringify(this.selectedRoomIds),
					setData:JSON.stringify(copyData)
				}).then(res => {
					uni.hideLoading();
					if (res.code === 1) {
						uni.showToast({ title: '复制成功', icon: 'success' });
						this.closeModal();
					} else {
						uni.showToast({ title: res.msg || '复制失败', icon: 'none' });
					}
				}).catch(() => {
					uni.hideLoading();
					uni.showToast({ title: '网络错误，请重试', icon: 'none' });
				});
			},
			
			// 关闭弹窗
			closeModal() {
				this.showCopyModal = false;
				this.rooms = [];
				this.selectedRoomIds = [];
				this.currentItem = null;
			}
		}
	}
</script>

<style lang="scss">
	// 基础样式
	.page {
		min-height: 100vh;
		box-sizing: border-box;
	}
	.text-center {
		text-align: center;
	}
	.text-white {
		color: white;
	}
	
	// 星期选择容器
	.days-container {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		flex: 1;
	}
	.day-btn {
		padding: 6rpx 12rpx;
		border: 1px solid #eee;
		border-radius: 6rpx;
		font-size: 26rpx;
		background-color: #f5f5f5;
		color: #333;
		&.selected {
			background-color: #ffaa00;
			color: white;
			border-color: #ffaa00;
		}
	}
	
	// 按钮组
	.btnGroup {
		gap: 18rpx;
		justify-content: flex-end
	}
	
	// 弹窗样式
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}
	.modal-container {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 85%;
		max-width: 500px;
		background-color: #fff;
		border-radius: 16rpx;
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}
	.modal-header {
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
	}
	.modal-close {
		font-size: 40rpx;
		color: #999;
	}
	.modal-content {
		padding: 30rpx;
		overflow-y: auto;
		flex: 1;
	}
	.loading, .no-data, .error {
		text-align: center;
		padding: 40rpx 0;
		color: #666;
		font-size: 28rpx;
	}
	.retry-btn {
		margin-top: 10rpx;
		padding: 8rpx 20rpx;
		font-size: 26rpx;
	}
	.room-list {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	.room-item {
		display: flex;
		align-items: center;
		padding: 15rpx;
		border-radius: 8rpx;
		background-color: #f9f9f9;
	}
	.room-name {
		margin-left: 15rpx;
		font-size: 28rpx;
	}
	.modal-footer {
		padding: 20rpx 30rpx;
		border-top: 1px solid #eee;
		display: flex;
		gap: 20rpx;
	}
	.modal-footer button {
		flex: 1;
		padding: 15rpx 0;
	}
	.disabled {
		opacity: 0.6;
	}
</style>
